#! /usr/bin/python

import urllib2

import datetime
print datetime.datetime.now()

webapikey = "XXXX"
urlcmd = "https://kokos.pl/webapi/get-recent-auctions?key="+webapikey+"&records=100&page=1"

resultxml = urllib2.urlopen(urlcmd).read()

#print resultxml


from xml.dom.minidom import parse, parseString

domxml = parseString( resultxml )

auctions = domxml.getElementsByTagName("auction")

all_auctions = {}
for auction in auctions:
	auct_dict = {}
	key_list = ["id","title", "value", "period", "createDate"] 	
	for k in key_list:
		auct_dict[k] = auction.getElementsByTagName(k)[0].childNodes[0].data
	all_auctions[ auct_dict["id"] ] = auct_dict


prev_maxid = 1
maxidfile = open( "/home/grzanka/usr/pykokos/maxid.txt", 'r')

prev_maxid = maxidfile.read()
print "prev max id ", prev_maxid

cur_maxid = max([int(k) for k in all_auctions.keys()])
print "cur max id ", cur_maxid

import webbrowser
if int(cur_maxid) > int(prev_maxid):
	for a in sorted(all_auctions, key=lambda key: all_auctions[key]):
		if (int(a) > int(prev_maxid)) and (int(a) <= int(cur_maxid)):
			print "new action ",a, all_auctions[a]
			url = "https://kokos.pl/aukcje?id=" + a
			webbrowser.open_new(url)
else:
	print "no new actions"

maxidfile = open( "/home/grzanka/usr/pykokos/maxid.txt", 'w')
maxidfile.write( str(cur_maxid) )
maxidfile.close( )

